<%@ page language="java" import="java.lang.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
<style type="text/css">
#container {
	width: 100%;
	position: absolute;
}
#bomTreeDiv {
	width: 205px;
	height: 100%;
	border-right: solid 1px #cdcfd0;
	float: left;
	padding-left: 30px;
	padding-right: 25px;
	padding-top: 10px;
	display: inline;
	box-sizing: border-box;
}
#grid-div {
	width: calc(100% - 220px);
	height: 100%;
	float: left;
}
</style>
<div id="head" class="row-fluid" style="border:0px;">
	<form id="bomForm" class="form-horizontal" target="_ifr" style="width:1000px;margin:10px auto;border-bottom: solid 2px #3b73af;">
		<div id="fromInfoContent">
			<input type="hidden" id="id" name="id" value="${bom.id }"> <input type="hidden" id="bomCreateTime" name="bomCreateTime" value="${bom.bomCreateTime }">
			<div class="row" style="margin:0;padding:0;">
	            <div class="control-group span6" style="display: inline">
	                <label class="control-label" for="bomNo" >BOM编号：</label>
	                <div class="controls">
	                    <div class="input-append  span12" >
	                        <input type="text" id="bomNo" class="span10" name="bomNo" placeholder="后台自动生成" readonly="readonly" value="${bom.bomNo}"/>
	                    </div>
	                </div>
	            </div>
	            <div class="control-group span6" style="display: inline">
	                <label class="control-label" for="bomName" >BOM名称：</label>
	                <div class="controls">
	                    <div class="input-append  span12 required" >
	                        <input type="text" id="bomName" class="span10" name="bomName" placeholder="BOM名称" value="${bom.bomName}"/>
	                    </div>
	                </div>
	            </div>
	        </div>
			<div  class="row" style="margin:0;padding:0;">
	            <div class="control-group span6" style="display: inline">
	                <label class="control-label" for="productId" >产&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;品：</label>
	                <div class="controls">
	                    <div class="required span12" style=" float: none !important;">                 
				            <input id="productId" class="span10" type="text" name="productId" value="">
	                    </div>
	                </div>
	            </div>
	            <div class="control-group span6" style="display: inline">
	                <label class="control-label" for="remark" >备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注：</label>
	                <div class="controls">
	                    <input type="text" class="span10" id="remark" name="remark" placeholder="备注" value="${bom.remark}"/>
	                </div>
	            </div>
	      </div>		
		</div>
		<div style="margin-left:30px;margin-bottom:10px;">
            <span class="btn btn-info" id="formSave" onclick="saveForm();">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
        </div>
	</form>
</div>
<div id="container">
	<div id="bomTreeDiv" class="ztree" style="overflow-y: auto;"></div>
	<div class="row-fluid" id="grid-div" style="position: relative; margin-top:0;">
		<div id="table_tools" style="margin-top: 0;border:20px;padding:0 3px;border-color: blue">
			<button class=" btn btn-primary btn-addQx" onclick="addMaterial();">
				添加<i class="fa fa-plus" aria-hidden="true" style="margin-left:5px;"></i>
			</button>
			<button class=" btn btn-primary btn-deleteQx" onclick="deletebom();">
				删除<i class="fa fa-trash" aria-hidden="true" style="margin-left:5px;"></i>
			</button>
		</div>
		<!-- 表格 -->
		<div class="row-fluid-m" style="padding:0 3px;">
			<!-- 表格数据 -->
			<table class="table" id="grid-table-m" style="width:100%;"></table>
			<!-- 表格底部 -->
			<div id="grid-pager-m"></div>
		</div>
	</div>
</div>
<script type="text/javascript">
var bomName="${bom.bomName}";
var currentBomId=${bomId};
var currentNode={id:0,pId:-1};
var selectTreeId=0;
var zTree = $.fn.zTree.getZTreeObj("bomTreeDiv");
var oriDatab;
var _gridb;
var $queryWindowb;  //查询窗口对象
var select_data = '';
var select_dataLocation = '';
var selectid = $("#grid-table").getRowData(jQuery("#grid-table").getGridParam("selarrrow")[0]).bomId;
$("#bomId1").val(selectid);
var routId=0;
var flag=0;
_gridb = jQuery("#grid-table-m").jqGrid({
        url: context_path + "/bom/bomDetailList.do?bomId="+${bomId},
        datatype: "json",
        colNames: ["主键", "编号","名称","供应商", "品牌", "生产商", "单价", "数量","属性"],
        colModel: [
            {name: "id", index: "id", hidden: true},
            {name: "bomDetailNo", index: "bomDetailNo", width: 40},
            {name: "bomDetailName", index: "bomDetailName", width: 50},
            {name: "supplier", index: "supplier", width: 60},
            {name: "brand", index: "brand",width:50},
            {name: "producer", index: "producer",width:50},
            {name: "price", index: "price" ,width:40},
            {name : "amount", index: "amount", width: 20,editable : true,editrules: {custom: true, custom_func: numberRegex},
                        editoptions: {
	                          size: 25,
	                          dataEvents: [
	                              {
	                                  type: "blur",     //blur,focus,change.............
	                                  fn: function (e) {
	                                	  var $element = e.currentTarget;
	                                	  var $elementId = $element.id;
	                                	  var rowid = $elementId.split("_")[0];
	                                	  var id=$element.parentElement.parentElement.children[1].textContent;
	                                	  var indocType = 1;
	                                	  var reg = new RegExp("^[1-9]+([0-9]{1,2})?$");
	                                	  if (!reg.test($("#"+$elementId).val())) {
	                                		  layer.alert("请输入正整数！");
	                                		  return false;
	                                	   }
	                                	  $.ajax({
	                                		  url:context_path + "/bom/saveAmount",
	                                		  type:"POST",
	                                		  data:{id:id,amount:$("#"+rowid+"_amount").val()},
	                                		  dataType:"json",
	                                		  success:function(data){
	                                		        if(Boolean(data)){
	                                		           $("#grid-table-m").jqGrid("setGridParam", 
                                							{
                                					    		url : context_path + "/bom/bomDetailList.do?pId="+currentNode.id,
                                								postData: {queryJsonString:""} //发送数据  :选中的节点
                                							}
                                					  ).trigger("reloadGrid");
                                					  layer.msg("保存数量成功！",{icon:1});
	                                		        }else{
	                                		        layer.alert("保存数量失败！",{icon:2});
	                                		        }	                                		                     		      
	                                		  }
	                                	  }); 
	                                  }
	                              }
	                          ]
	                      }
                      },
            {name :"type",index:"type",width:40,               
                formatter: function (value,options,rowObject){
                    if (typeof value == "number") {
                    if(value==0){
           			return "<span style='font-weight:bold;'>物料</span>" ;
           		}else if(value==1){
           			return "<span style='font-weight:bold;'>类别</span>" ;
           		}
                    }else{
                    return "" ;
                    }
                }
             }
        ],
        onCellSelect : function(ts,ri,ci,tdHtml,e){       
            if(ri != 6) {
                return;
            }
            var rowData =  $("#grid-table-m").jqGrid("getRowData",ts);
            var routName=rowData.routeId;
            if(routName!=""){
                if(flag==1){
                    flag=0;
                }else{
                    var da=select_data;
                    for (let i = 0; i < da.result.length; i++) {
                        if(da.result[i].routeName==routName){
                            routId=da.result[i].id;
                            this.p.colModel[ri].editoptions.value = gettypesLocation(routId);
                        }
                    }
                }
            }else{
            }
        },       
        rowNum: 20,
        rowList: [10, 20, 30],
        pager: "#grid-pager-m",
        sortname: "id",
        sortorder: "desc",
        altRows: true,
        viewrecords: true,
        hidegrid: false,
        multiselect: true,
        width: 850,
        loadComplete: function (data) {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
                enableTooltips(table);
            }, 0);
            oriDatab = data;
        },
        cellurl: context_path + "/bom/saveAmount",
        cellEdit: true,
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext: "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据"
    });

    /*动态计算表格宽度高度 -- cy 2017-11-6 */
	$(window).on('resize.jqGrid', function () {
	     $("#grid-table-m").jqGrid( 'setGridWidth', _gridb.parents("#grid-div").width());
	     var height=$("#head").outerHeight(true)+
        $("#table_tools").outerHeight(true)+
        $("#grid-pager-m").outerHeight(true)+
        $("#gview_grid-table-m .ui-jqgrid-hbox").outerHeight(true)+
        $(".layui-layer-title").outerHeight(true);
        
        $("#grid-table-m").jqGrid("setGridHeight",  _gridb.parents(".layui-layer").height()-height);
	});
	$(window).triggerHandler('resize.jqGrid');
	
	//计算Tree的高度
	$("#container").css("height", _gridb.parents(".layui-layer").height() 
   		 -  $(".layui-layer-title", _gridb.parents(".layui-layer") ).height() 
		 -  $("#bomForm").outerHeight(true));
    /*动态计算表格宽度高度 --end   */
    
    jQuery("#grid-table-m").navGrid('#grid-pager-m', {
        edit: false,
        add: false,
        del: false,
        search: false,
        refresh: false
    }).navButtonAdd('#grid-pager-m', {
            caption: "",
            buttonicon: "fa fa-refresh green",
            onClickButton: function () {
                $("#grid-table-m").jqGrid('setGridParam',
                    {
                        postData: {queryJsonString: ""} //发送数据
                    }
                ).trigger("reloadGrid");
            }
    });
function initTree(bomId) {
    $.ajax({
           type : "POST",
   		url : context_path + "/bom/allTreeData?parentId="+selectTreeId+"&bomId="+bomId,
   		dataType : "json",
   		cache : false,
   		success : function(dataJson) {
   			             console.dir(dataJson);
   					     dataJson.push({
   						       id : 0,
   						       pId : -1,
   						       text : bomName,
   						       open : true
   					           });
                             zTree = $.fn.zTree.init($("#bomTreeDiv"), setting,dataJson);
                             zTree.expandAll(true);					
   				}
     });
}
$(document).ready(function() {       
    initTree(${bomId});
}); 
function deletebom() {
    var selectAmount = getGridCheckedNum("#grid-table-m");
    if (selectAmount == 0) {
        layer.msg("请选择一条记录！", {icon: 2});
        return;
    }
    var idAddr = jQuery("#grid-table-m").getGridParam("selarrrow");
    var _ids = "";
    if (idAddr && idAddr.length > 0) {
        for (var i = 0; i < idAddr.length; i++) {
            var _value = idAddr[i];
             _ids += ((_ids == "") ? "" : ",") + _value;
        }
    }
    var id = _ids;
    layer.confirm("确定删除？", /*显示的内容*/
        {
            shift: 6,
            moveType: 1, //拖拽风格，0是默认，1是传统拖动
            title: "操作提示", /*弹出框标题*/
            icon: 3, /*消息内容前面添加图标*/
            btn: ["确定", "取消"]/*可以有多个按钮*/
        }, function (index, layero) {
            $.ajax({
                url: context_path + "/bom/deleteDetail",
                type: "POST",
                data: {ids: id},
                dataType: "json",
                success: function (data) {
                    if (data) {
                        layer.msg("操作成功!", {icon: 1});
                        refreshTree();
                        $("#grid-table-m").jqGrid('setGridParam',
                            {
                                postData: {queryJsonString: ""} //发送数据
                            }
                        ).trigger("reloadGrid");
                        layer.close(index);
                    } else {
                        layer.msg("操作失败!", {icon: 2});
                    }
                }
            });
        }, function (index) {
            layer.close(index);
        });
} 
function zTreeOnClick(event, treeId, treeNode){
    currentNode.id=treeNode.id;
	currentNode.pId=treeNode.pId;
	reload_device(treeNode.id, treeNode.pId,"");
}
function reload_device(id,pId, queryJsonString) {
    $("#grid-table-m").jqGrid("setGridParam",
        {
            postData: {queryJsonString: "",pId:id,bomId:${bomId}} //发送数据
        }
    ).trigger("reloadGrid");
} 
var setting = {
        data : {
                simpleData : {
                    enable : true,
                    idKey : "id",
                    pIdKey : "pId"
                },
                key : {
                    name : "text"
                }
            },
            callback : {
                onClick : zTreeOnClick
            },
        async: {
            enable: true,
            url:context_path+"/bom/allTreeData",
            autoParam:["id"],
            otherParam:{"parentId":function (){
                return currentNode.id;},"bomId":function (){
                return currentBomId;}},
            type: "POST"
        }
};
$("#bomForm .mySelect2").select2();
    function saveForm() {
        var bean = $("#bomForm").serialize();
        if ($("#bomForm").valid()) {
            saveBom(bean);
        }
    }
	$("#bomForm").validate({
		ignore:"",
		rules:{
			"bomName":{//供应商编号
  				required:true,
  				maxlength:50,
  				remote:"<%=path%>/bom/existsBomName?bomName="+$("#bomName").val()+"&bomId="+$("#id").val()
  			},
            "productId":{
                required:true
            }
  		},
  		messages:{
  			"bomName":{
  				required:"请输入bom名称！",
  				maxlength:"长度不能超过50个字符！",
  				remote:"您输入的bom名称已经存在，请重新输入！"
  			},
            "productId":{
                required:"请选择产品！"
            } 
  		},
  		errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
           $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
           $(element).parents('.control-group').removeClass('error');
        }
  	});
function refreshTree() {
	var node=zTree.getNodeByParam("id",currentNode.id);
    node.isParent = true;
    zTree.reAsyncChildNodes(node, "refresh",false);
}
function saveBom(bean) {
        $.ajax({
            url: context_path + "/bom/saveBom",
            type: "POST",
            data: bean,
            dataType: "JSON",
            success: function (data) {
                if (Boolean(data.result)) {
                    layer.msg("表头保存成功！", {icon: 1});
                    currentBomId=data.bomId;
                    bomName=data.bomName;
                    initTree(currentBomId);
                    currentNode.id=0;
                    $("#grid-table").jqGrid("setGridParam",
                        {
                            postData: {queryJsonString: ""} //发送数据
                        }
                    ).trigger("reloadGrid");
                    $("#bomForm #id").val(data.bomId);
                    $("#bomForm #bomNo").val(data.bomNo);
                    selectid = data.bomid;
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            }
        });
    }
    $(window).triggerHandler('resize.jqGrid');
    //重新加载表格
    function gridReload() {
        _gridb.trigger("reloadGrid");  //重新加载表格
    }

    //选择生产流程
    $("#materialType").select2({
        placeholder: "选择产品类型",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/bom/getProductType",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });   
    var parentId='';
    //添加物料按钮验证
    function addMaterial() {
        if(currentNode.pId>0){
            layer.msg("物料最只能添加两级！",{icon:8});
            return;
        }
    	parentId = currentNode.id;
        var bean = $("#bomForm").serialize();
        $.ajax({
            url: context_path + "/bom/headerSaved?parentId="+parentId+"&bId="+$("#bomForm #id").val(),
            type: "POST",
            data: bean,
            dataType: "JSON",
            success: function (data) {
                if (Boolean(data.result)) {
                    selectid = data.bomId;
                    layer.load(3);
                    $.post(context_path + "/bom/toAddMaterial.do?selectid="+selectid+"&parentId="+parentId, {}, function (str) {
                        $queryWindow = layer.open({
                            title: "清单物料添加",
                            type: 1,
                            skin: "layui-layer-molv",
                            area: "500px",
                            shade: 0.6, //遮罩透明度
                            moveType: 1, //拖拽风格，0是默认，1是传统拖动
                            content: str,//注意，如果str是object，那么需要字符拼接。
                            success: function (layero, index) {
                                layer.closeAll('loading');
                            }
                        });
                    }).error(function () {
                        layer.closeAll();
                        layer.msg("加载失败！", {icon: 2});
                    });
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            }
        });
    }
    
    //数量输入验证
    function numberRegex(value, colname) {
        var regex = /^\d+\.?\d{0,2}$/;
        if (!regex.test(value)) {
            return [false, "请输入正整数!"];
        }
        return [true, ""];
    }
    $("#bomForm #productId").select2({
        placeholder: "选择产品",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        width:305,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/material/getMaterialSelectList",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
    $.ajax({
	 type:"POST",
	 url:context_path + "/bom/findById",
	 data:{id:$("#bomForm #id").val()},
	 dataType:"json",
	 success:function(data){
			  $("#bomForm #productId").select2("data", {
 			  id: data.productId,
 			  text: data.productTypeName
             }); 
		}
	});
		
</script>